<template>
  <el-autocomplete v-scrollLoad="load" ref="autocomplete" popper-class="my-autocomplete" v-model="state"
    :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect">
    <i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClick">
    </i>
    <template slot-scope="{ item }">
      <div class="name">{{ item.value }}</div>
      <span class="addr">商品Id ：{{ item.productId }}</span>
    </template>
  </el-autocomplete>
</template>

<script>



export default {
  model: {
    prop: "value", // 默认是 value
    event: "input", // 默认是 input
  },
  props: {
    value: {
      type: Number,
      default: 0,
    },
  },

  data() {
    return {
      state: '',
      pageIndex: 1,
      pageSize: 10,
      // 加载标志位，判断是否加载到了底部
      loadEnd: false
    };

  },
  methods: {

    // 获取数据列表
    async getDataList() {
      return await this.$http({
        url: this.$http.adornUrl('/product/product/list'),
        method: 'get',
        params: this.$http.adornParams({
          'key': this.state,
          'page': this.pageIndex,
          'limit': this.pageSize,

        })
      }).then(({ data }) => {
        console.log("获取商品列表成功", data);

        if (data && data.code === 200) {
          return data.page.list
        } else {
          return []
        }
      })
    },

    //获取分类数据列表
    async getCategoryList() {
      return await this.$http({
        url: this.$http.adornUrl('/product/product/info/' + this.value),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        console.log("获取商品数据成功", data);
        if (data && data.code === 200) {
          console.log(data);

          return data.product;

        }
      })
    },

    async querySearch(queryString, cb) {

      var result = await this.getDataList();
      this.loadEnd = false
      this.pageIndex = 1
      this.pageSize = 10

      result.forEach(element => {
        element.value = element.title
      });
      console.log('result', result);
      // 调用 callback 返回建议列表的数据
      cb(result);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },


    // 加载更多
    async load() {

      if (this.loadEnd) {
        console.log("暂无更多")
        this.$message('暂无更多');
        return
      }
      // 添加分页页数
      this.pageIndex += 1;
      var result = await this.getDataList();
      // 遍历赋值到vlaue
      result.forEach(element => {
        element.value = element.title
      });

      // 判断获取到的数据是否为空，修改标志位
      console.log("获取分页数据", result);
      if (result.length == 0) {
        console.log("暂无更多")
        this.loadEnd = true
        retuen
      }
      // 将获取到的推荐数据添加到推荐列表中
      this.$refs['autocomplete'].$data.suggestions.push(...result)
      console.log("autocomplete", this.$refs['autocomplete'].$data.suggestions);

    },
    handleSelect(item) {
      console.log(this.state);
      this.$emit('input', item.productId)
      this.$emit('getProductTitle', item.title)
    },
    handleIconClick(ev) {
      console.log(ev);
    }
  },
  watch: {
    async value(newVal, oldVal) {
      // console.log("旧值", oldVal);
      // console.log("新值", newVal);

      // 当更新后的值是大于0，就是合法值，则查询数据更新
      if (newVal != 0) {
        console.log("新值", newVal);
        const productItem = await this.getCategoryList()

        console.log('productItem', productItem);
        this.state = productItem.title

        // 更新父组件的数据
        this.$emit('input', productItem.productId)
        this.$emit('getProductTitle', productItem.title)
        return
      }


      // 为0表示恢复默认值
      console.log("新值", 0);
      this.state = ''
      // 更新父组件的数据
      this.$emit('input', 0)
      this.$emit('getProductTitle', '')
      // newVal是新值，oldVal是旧值
      // 这里可以执行任何响应变化的操作
    }
  },

  //自定义指令
  directives: {
    //用户选择栏的懒加载
    scrollLoad: {
      bind(el, binding, vnode) {
        //防抖函数
        function debounce(func, wait, immediate) {
          //func函数，wait为时间周期
          var timeout;
          return function () {
            var context = this,
              args = arguments;
            var later = function () {
              timeout = null;
              if (!immediate) {
                func.apply(context, args);
              }
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) {
              func.apply(context, args);
            }
          };
        }
        let wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap');
        let listDom = el.querySelector('.el-autocomplete-suggestion__wrap  .el-autocomplete-suggestion__list');
        //将滚动事件通过参数传入防抖函数中
        var myEfficientFn = debounce(function () {
          let condition = wrapDom.offsetHeight + wrapDom.scrollTop + 10 - listDom.offsetHeight;
          if (condition > 0 && !vnode.context.loading) {
            //滚动到底部则执行滚动方法load，binding.value就是v-scrollLoad绑定的值，加()表示执行绑定的方法
            binding.value();
          }
        }, 250);
        wrapDom.addEventListener('scroll', myEfficientFn, false); //绑定滚动事件
      }
    }
  },

}
</script>

<style lang="scss">
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }

    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
